<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="商品名称">
        <el-input v-model="goodsInfo.name" placeholder=" 示例：华为手机P40" />
      </el-form-item>

      <!-- 所属分类 TODO -->
      <el-form-item label="商品分类">
        <el-select
          v-model="goodsInfo.categoryFirst"
          placeholder="一级分类"
          @change="subjectLevelOneChanged"
        >
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.name"
            :value="subject.id"
          />
        </el-select>

        <!-- 二级分类 -->
        <el-select v-model="goodsInfo.categorySecond" placeholder="二级分类">
          <el-option
            v-for="subject in subjectOneHasChildren"
            :key="subject.id"
            :label="subject.name"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <!-- 是否上架 -->
      <el-form-item label="是否上架">
        <el-select v-model="goodsInfo.shelf" placeholder="请选择">
          <el-option
            v-for="shelf in shelfList"
            :key="shelf.id"
            :label="shelf.name"
            :value="shelf.id"
          />
        </el-select>
      </el-form-item>

      <!-- 库存-->
      <el-form-item label="库存">
        <el-input-number
          :min="0"
          v-model="goodsInfo.stock"
          controls-position="right"
          placeholder="请填写库存数量"
        />
      </el-form-item>

      <!-- 销售价-->
      <el-form-item label="销售价">
        <el-input-number
          :min="0"
          v-model="goodsInfo.salesPrice"
          controls-position="right"
          placeholder="请填写销售价"
        />
      </el-form-item>

      <!-- 市场价-->
      <el-form-item label="市场价">
        <el-input-number
          :min="0"
          v-model="goodsInfo.marketPrice"
          controls-position="right"
          placeholder="请填写市场价"
        />
      </el-form-item>

      <!-- 成本价-->
      <el-form-item label="成本价">
        <el-input-number
          :min="0"
          v-model="goodsInfo.costPrice"
          controls-position="right"
          placeholder="请填写成本价"
        />
      </el-form-item>

      <!-- 销售量-->
      <el-form-item label="销售量（虚拟）">
        <el-input-number
          :min="0"
          v-model="goodsInfo.saleNum"
          controls-position="right"
          placeholder="请填写销售量"
        />
      </el-form-item>

      <!-- 卖点 -->
      <el-form-item label="商品卖点">
        <el-input
          v-model="goodsInfo.sellPoint"
          placeholder=" 示例：华为手机P40很好"
        />
      </el-form-item>

      <!-- 商品简介-->
      <el-form-item label="商品简介">
        <tinymce :height="300" v-model="goodsInfo.description" />
      </el-form-item>

      <!-- 商品封面-->
      <el-form-item label="商品封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API + '/eduoss/fileoss'"
          class="avatar-uploader"
        >
          <img :src="goodsInfo.picUrls" />
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import course from "@/api/goods";
import subject from "@/api/subject";
import Tinymce from "@/components/Tinymce"; // 引入富文本组件
export default {
  // 声明组件
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false,
      goodsInfo: {
        name: "",
        categoryFirst: "", // 一级分类id
        categorySecond: "", // 二级分类id
        shelf: "",
        sellPoint: "", // 卖点
        stock: 0,
        salesPrice: 0.0,
        marketPrice: 0.0,
        costPrice: 0.0,
        saleNum: 0,
        description: "",
        picUrls: "/static/01.jpg",
      },
      id: "", // 商品id
      BASE_API: process.env.BASE_API, // 接口API地址
      shelfList: [
        { id: 0, name: "否" },
        { id: 1, name: "是" },
      ], // 是否上架
      subjectOneList: [], // 所有一级分类
      subjectTwoList: [], // 所有二级分类
      subjectOneHasChildren: [], // 每个一级分类所对应的二级分类
    };
  },
  created() {
    // 获取路由页面传递得参数，如有参数，则是更新
    if (this.$route.params && this.$route.params.id) {
      this.id = this.$route.params.id;
      // 调用获取课程内容接口,即回显
      this.getGoodsInfoById();
    } else {
      // 新增
      // 清空表单
      this.goodsInfo = {
        name: "",
        categoryFirst: "", // 一级分类id
        categorySecond: "", // 二级分类id
        shelf: "",
        stock: 0,
        salesPrice: 0.0,
        marketPrice: 0.0,
        costPrice: 0.0,
        saleNum: 0,
        description: "",
        picUrls: "/static/01.jpg",
      };
      // 初始化一级分类
      this.getOneSubject();
    }
  },
  methods: {
    // 根据课程id查询课程信息
    getGoodsInfoById() {
      course.findById(this.id).then((response) => {
        // 获取产品信息
        this.goodsInfo = response.data.item;

        // 调用获取所有的一级分类接口，获取所有的以及分类
        subject.findAll().then((response) => {
          // 1. 获取所有的一级分类
          let list = response.data.list;
          this.getFirstCategory(list);
          // 2. 获取所有二级分类
          this.getSecondCategory(list);
          // 3. 获取当前商品所属分类及其所有二级分类
          for (var i = 0; i < this.subjectTwoList.length; i++) {
            var item = this.subjectTwoList[i];
            if (this.goodsInfo.categoryFirst == item.parentId) {
              this.subjectOneHasChildren.push(item);
            }
          }
        });
      });
    },
    // 上传封面成功调用的方法
    handleAvatarSuccess(res, file) {
      this.goodsInfo.picUrls = res.data.url;
    },
    // 上传之前调用的方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 点击某个一级分类，触发change，显示对应二级分类
    subjectLevelOneChanged(value) {
      // 先清空
      this.subjectOneHasChildren = [];
      this.goodsInfo.categorySecond = "";

      for (var i = 0; i < this.subjectTwoList.length; i++) {
        var item = this.subjectTwoList[i];
        if (value == item.parentId) {
          this.subjectOneHasChildren.push(item);
        }
      }
    },
    // 查询所有的分类
    getOneSubject() {
      subject.findAll().then((response) => {
        let list = response.data.list;
        // 1. 获取所有的一级分类
        this.getFirstCategory(list);
        // 2. 获取所有二级分类
        this.getSecondCategory(list);
      });
    },
    // 获取一级分类
    getFirstCategory(list) {
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        let pid = item.parentId;
        if (pid == null || pid == "") {
          this.subjectOneList.push(item);
        }
      }
    },
    // 获取二级分类
    getSecondCategory(list) {
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        let pid = item.parentId;
        if (pid != null && pid != "") {
          for (let j = 0; j < this.subjectOneList.length; j++) {
            let subject01 = this.subjectOneList[j];
            if (pid == subject01.id) {
              this.subjectTwoList.push(item);
            }
          }
        }
      }
    },
    // 新增课程
    addCourse() {
      course.add(this.goodsInfo).then((response) => {
        // 提示
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        // 跳转到列表页
        this.$router.push({ path: "/goods/list" });
      });
    },
    // 修改课程
    updateCourse() {
      course.update(this.goodsInfo).then((response) => {
        // 提示
        this.$message({
          type: "success",
          message: "修改信息成功!",
        });
        // 跳转到第二步
        this.$router.push({ path: "/goods/list" });
      });
    },
    saveOrUpdate() {
      if (!this.goodsInfo.id) {
        // 新增
        this.addCourse();
      } else {
        // 修改
        this.updateCourse();
      }
    },
  },
};
</script>
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>
